package com.ds.dsm.view.entity;

import com.ds.common.JDSConstants;
import com.ds.common.JDSException;
import com.ds.common.logging.Log;
import com.ds.common.logging.LogFactory;
import com.ds.common.util.StringUtility;
import com.ds.config.ErrorListResultModel;
import com.ds.config.ListResultModel;
import com.ds.config.ResultModel;
import com.ds.config.TreeListResultModel;
import com.ds.dsm.view.config.tree.ViewConfigTree;
import com.ds.enums.db.MethodChinaName;
import com.ds.esd.custom.ESDClass;
import com.ds.esd.custom.annotation.CustomAnnotation;
import com.ds.esd.custom.annotation.DialogAnnotation;
import com.ds.esd.custom.annotation.GridViewAnnotation;
import com.ds.esd.custom.annotation.PopTreeViewAnnotation;
import com.ds.esd.custom.api.annotation.APIEventAnnotation;
import com.ds.esd.custom.api.enums.CustomCallBack;
import com.ds.esd.custom.enums.CustomMenuItem;
import com.ds.esd.custom.module.annotation.ModuleAnnotation;
import com.ds.esd.custom.nav.annotation.NavGroupViewAnnotation;
import com.ds.esd.custom.nav.annotation.NavTreeViewAnnotation;
import com.ds.esd.dsm.DSMFactory;
import com.ds.esd.dsm.view.ViewInst;
import com.ds.esd.tool.ui.enums.Dock;
import com.ds.esd.util.TreePageUtil;
import com.ds.web.annotation.AggregationType;
import com.ds.web.util.PageUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(path = "/dsm/view/config/entity/")
@MethodChinaName(cname = "视图实体", imageClass = "spafont spa-icon-c-gallery")

public class ViewEntityService {
    protected Log log = LogFactory.getLog(JDSConstants.CONFIG_KEY, ViewEntityService.class);

    @CustomAnnotation(pid = true, hidden = true)
    String viewInstId;
    @CustomAnnotation(pid = true, hidden = true)
    String domainId;
    @CustomAnnotation(pid = true, hidden = true)
    String projectVersionName;


    @MethodChinaName(cname = "视图信息")
    @RequestMapping(method = RequestMethod.POST, value = "ViewEntityList")
    @GridViewAnnotation
    @ModuleAnnotation(imageClass = "spafont spa-icon-c-buttonview", caption = "视图信息")
    @APIEventAnnotation(autoRun = true, bindMenu = CustomMenuItem.reload)
    @ResponseBody
    public ListResultModel<List<ViewEntityGridView>> getViewEntityList(String viewInstId) {
        ListResultModel<List<ViewEntityGridView>> result = new ListResultModel();
        try {
            ViewInst bean = DSMFactory.getInstance().getViewManager().getViewInstById(viewInstId);
            if (bean != null) {
                List<ESDClass> esdClassList = bean.getViewProxyClasses();
                result = PageUtil.getDefaultPageList(esdClassList, ViewEntityGridView.class);
            }
        } catch (JDSException e) {
            result = new ErrorListResultModel<>();
            ((ErrorListResultModel) result).setErrcode(e.getErrorCode());
            ((ErrorListResultModel) result).setErrdes(e.getMessage());
        }
        return result;
    }


    @MethodChinaName(cname = "视图信息")
    @RequestMapping(method = RequestMethod.POST, value = "ViewEntityInfo")
    @NavGroupViewAnnotation
    @ModuleAnnotation(dock = Dock.fill, caption = "装载", imageClass = "spafont spa-icon-c-grid")
    @ResponseBody
    public ResultModel<ViewInfoGroup> getViewEntityInfo(String viewInstId, String domainId, String sourceClassName) {
        ResultModel<ViewInfoGroup> result = new ResultModel<ViewInfoGroup>();
        return result;
    }

    @MethodChinaName(cname = "添加控制接口")
    @RequestMapping(value = {"ViewEntityTree"}, method = {RequestMethod.GET, RequestMethod.POST})
    @CustomAnnotation(dock = Dock.fill)
    @PopTreeViewAnnotation
    @DialogAnnotation
    @ModuleAnnotation(width = "400", caption = "添加控制接口", dynLoad = true)
    @APIEventAnnotation(isAllform = true, autoRun = true, bindMenu = CustomMenuItem.add)
    @ResponseBody
    public TreeListResultModel<List<ViewEntityTree>> getViewEntityTree(String viewInstId) {
        TreeListResultModel<List<ViewEntityTree>> result = new TreeListResultModel<List<ViewEntityTree>>();

        AggregationType[] aggregationTypes = new AggregationType[]{
                AggregationType.customapi,
                AggregationType.aggregationEntity,
                AggregationType.aggregationRoot,
                AggregationType.menu,
                AggregationType.view,
                AggregationType.aggregationSet,
                AggregationType.customDomain
        };

        result = TreePageUtil.getTreeList(Arrays.asList(aggregationTypes), ViewEntityTree.class);

        return result;
    }

    @MethodChinaName(cname = "保存控制接口")
    @RequestMapping(value = {"saveViewEntity"}, method = {RequestMethod.GET, RequestMethod.POST})
    @APIEventAnnotation(isAllform = true, callback = {CustomCallBack.ReloadParent, CustomCallBack.Close}, bindMenu = CustomMenuItem.save)
    public @ResponseBody
    ResultModel<Boolean> saveViewEntity(String viewInstId, String ViewEntityTree) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();
        if (ViewEntityTree != null) {
            try {
                ViewInst bean = DSMFactory.getInstance().getViewManager().getViewInstById(viewInstId);
                if (bean != null) {
                    String[] esdClassNames = StringUtility.split(ViewEntityTree, ";");
                    Map<String, String> entityMap = new HashMap<>();
                    for (String entityViewName : esdClassNames) {
                        if (entityViewName.indexOf(":") > -1) {
                            String className = StringUtility.split(entityViewName, ":")[0];
                            String domainId = StringUtility.split(entityViewName, ":")[1];
                            entityMap.put(className, domainId);
                        }
                    }
                    DSMFactory.getInstance().getViewManager().addViewEntity(viewInstId, entityMap);
                }

            } catch (JDSException e) {
                e.printStackTrace();
            }
        }
        return result;

    }

    @MethodChinaName(cname = "删除实体关系")
    @RequestMapping(value = {"delViewEntity"}, method = {RequestMethod.GET, RequestMethod.POST})
    @APIEventAnnotation(callback = {CustomCallBack.Reload}, bindMenu = CustomMenuItem.delete)
    public @ResponseBody
    ResultModel<Boolean> delViewEntity(String viewInstId, String ctClassName) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();
        if (viewInstId != null) {
            try {
                ViewInst bean = DSMFactory.getInstance().getViewManager().getViewInstById(viewInstId);

                Map<String, String> classNameMap = bean.getViewEntityMap();
                String[] classNames = StringUtility.split(ctClassName, ";");


                for (String esdClassName : classNames) {
                    try {
                        String className = StringUtility.split(esdClassName, ":")[0];
                        String domainId = StringUtility.split(esdClassName, ":")[1];

                        String sourceClassName = DSMFactory.getInstance().getViewManager().changeSourceClass(className, viewInstId);
                        if (!sourceClassName.equals(className)) {
                            classNameMap.remove(sourceClassName);
                            DSMFactory.getInstance().getViewManager().delViewEntity(sourceClassName, viewInstId);
                        }
                        classNameMap.remove(className);
                        DSMFactory.getInstance().getViewManager().delViewEntity(className, viewInstId);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
                DSMFactory.getInstance().getViewManager().updateViewInst(bean, true);
            } catch (JDSException e) {
                e.printStackTrace();
            }
        }
        return result;

    }


    @RequestMapping(method = RequestMethod.POST, value = "ViewEntityMetaView")
    @APIEventAnnotation(autoRun = true, bindMenu = CustomMenuItem.editor)
    @NavTreeViewAnnotation
    @DialogAnnotation(caption = "视图配置", width = "900", height = "680")
    @ModuleAnnotation(imageClass = "spafont spa-icon-c-cssbox", dynLoad = true, index = 1)
    @ResponseBody

    public TreeListResultModel<List<ViewConfigTree>> getViewEntityMetaView(String viewInstId, String domainId, String sourceClassName) {
        TreeListResultModel<List<ViewConfigTree>> result = new TreeListResultModel<>();
        result = TreePageUtil.getTreeList(Arrays.asList(sourceClassName), ViewConfigTree.class);
        return result;
    }

//    public TreeListResultModel<List<ViewConfigTree>> getViewEntityMetaView(String sourceClassName, String viewInstId, String domainId, String id) {
//        TreeListResultModel<List<ViewConfigTree>> resultModel = new TreeListResultModel<List<ViewConfigTree>>();
//        try {
//
//            ApiClassConfig customESDClassAPIBean = DSMFactory.getInstance().getViewManager().getViewEntityConfig(sourceClassName, viewInstId).getCurrConfig();
//            List<MethodConfig> customMethods = customESDClassAPIBean.getAllMethods();
//            List<CustomView> customViews = new ArrayList<>();
//            for (MethodConfig methodAPIBean : customMethods) {
//                if (methodAPIBean.getView() != null) {
//                    customViews.add(methodAPIBean.getView());
//                }
//            }
//
//
//
//            resultModel = TreePageUtil.getTreeList(customViews, ViewConfigTree.class);
//
//        } catch (JDSException e) {
//            e.printStackTrace();
//        }
//        return resultModel;
//
//    }

    public String getDomainId() {
        return domainId;
    }

    public void setDomainId(String domainId) {
        this.domainId = domainId;
    }

    public String getProjectVersionName() {
        return projectVersionName;
    }

    public void setProjectVersionName(String projectVersionName) {
        this.projectVersionName = projectVersionName;
    }

    public String getViewInstId() {
        return viewInstId;
    }

    public void setViewInstId(String viewInstId) {
        this.viewInstId = viewInstId;
    }
}
